// ==UserScript==
// @name         追放H5活动脚本 - 莱娅
// @namespace    http://tampermonkey.net/
// @version      0.0.3-2025-04-06
// @description  自动拼图，自动抽奖
// @match        https://gf2.sunborngame.com/lydjypt/*
// @icon         https://gf2-cn.cdn.sunborngame.com/website/official/laiya_h5/head.png
// @grant        GM_xmlhttpRequest
// @connect      gf2-h5ump45gacha-api.sunborngame.com
// @author       AgMonk
// @homepage     https://gitee.com/AgMonk/tampermonkey-script
// @downloadURL https://gitee.com/AgMonk/tampermonkey-script/raw/master/gf2/event-ump45.user.js
// @updateURL https://gitee.com/AgMonk/tampermonkey-script/raw/master/gf2/event-ump45.user.js
// @require      https://gitee.com/AgMonk/tampermonkey-script/raw/master/libs/crypto-js.min.js

// ==/UserScript==

(function () {
    const TAG = "[莱娅活动]";
    const md5 = (password) => CryptoJS.MD5(password).toString()
    // 发送请求
    let token = ''

    const request = (url, method = 'GET', body = undefined) => {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method, url,
                headers: {
                    "Content-Type": "application/json",
                    "authorization": token
                },
                data: body && JSON.stringify(body),
                onload: function (response) {
                    try {
                        let data = JSON.parse(response.responseText);
                        resolve(data.data); // 请求成功，解决 Promise
                    } catch (error) {
                        reject(error); // 解析 JSON 失败，拒绝 Promise
                    }
                },
                onerror: function (error) {
                    reject(error); // 请求失败，拒绝 Promise
                }
            });
        });
    }

    const baseUrl = "https://gf2-h5ump45gacha-api.sunborngame.com"
    const username = localStorage.getItem('username')
    const password = localStorage.getItem('password')
    if (!username || !password) console.warn(TAG, "未设置用户名或密码, 中断执行")

    // 查询活动信息
    const getInfo = async () => await request(`${baseUrl}/info`)
    const gacha = async () => await request(`${baseUrl}/gacha`, 'POST', {})
    const playClick = async (index) => await request(`${baseUrl}/play_click`, 'POST', {index})
    const refresh = async () => await request(`${baseUrl}/refresh`, 'POST', {})
    const login = async () => await request(`${baseUrl}/login`, 'POST', {
        account_name: username,
        passwd: md5(password),
        source: username.includes('@') ? 'mail' : 'phone'
    })

    const autoGacha = async () => {
        console.log(TAG, "开始自动抽卡")
        let count = (await getInfo()).gacha_num;
        console.log(TAG, `剩余抽卡次数:${count}`)
        if (count === 0) return

        const rewards = []
        for (let i = 0; i < count; i++) {
            let res = await gacha();
            rewards.push(res.name)
        }
        alert(`抽卡结果:\n${rewards.join('\n')}`)
    }

    const autoPlay = async () => {
        console.log(TAG, "开始自动拼图")

        // 当前信息，如果可得分为0 ，不执行
        let res = await getInfo();
        let dayCanGetScore = res.day_can_get_score
        if (dayCanGetScore === 0) {
            alert("当前可获取分数为0")
            return
        }
        let current = res.play_info.info
        console.log(TAG, '可获取分数', dayCanGetScore)
        console.log(TAG, '当前拼图', current)
        // 实际拼图
        const real = [...current]

        // 遍历空缺的部分
        for (let i = 0; i < real.length; i++) {
            if (real[i] === '') {
                let res = await playClick(i);
                current = res.play_info.info
                real[i] = res.card_id
            }
        }
        console.log(TAG, '实际拼图', real)

        // 奇数时落单的卡片ID
        let cardId = ""
        // 奇数时落单的卡片位置
        let cardIndex = -1
        // 剩余游玩次数
        let playTimes = 0
        //  剩余步数
        let times = 0
        // 如果当前棋盘有未翻开的位置，循环执行如下操作
        while (current.includes('')) {
            // 棋盘的翻开数
            let openCount = current.filter(item => item !== '').length
            if (openCount % 2 === 0) {
                // 如果当前棋盘的翻开数为偶数，翻开第一个空缺位置
                const index = current.indexOf("")
                const res = await playClick(index)
                // 更新当前棋盘
                current = res.play_info.info
                times = res.play_info.times

                // 更新落单的卡片ID和位置
                cardId = res.card_id
                cardIndex = index
                playTimes = res.play_times
            } else {
                // 如果当前棋盘的翻开数为奇数，从实际棋盘中找到另一张落单的卡牌的位置，翻开
                const i1 = real.indexOf(cardId)
                const i2 = real.lastIndexOf(cardId)
                const targetIndex = [i1, i2].find(i => i !== cardIndex)
                const res = await playClick(targetIndex)
                // 更新当前棋盘
                current = res.play_info.info
                // 更新落单的卡片ID和位置
                cardId = ""
                cardIndex = -1
                playTimes = res.play_times
                times = res.play_info.times
            }
            console.log(TAG, '当前拼图', current)
        }
        console.log(TAG, `拼图完毕，剩余步数: ${times}`)
        dayCanGetScore -= times * 10
        if (dayCanGetScore > 0) {
            await refresh()
            await autoPlay()
        } else {
            alert("已获取所有分数")
        }
    }

    // 登录
    setTimeout(() => {
        login().then(res => {
            token = res.account.token
            console.log(token.substring(0, 10))
            console.log(TAG, "登录成功")
        }).catch(() => {
            console.warn(TAG, "登录失败")
        })
    }, 200)


    setInterval(() => {
        const pathname = window.location.pathname

        // 当前处于抽卡页面，添加自动抽卡按钮
        if (pathname === '/lydjypt/luckyDraw') {
            // 按钮ID
            const id = 'auto_gacha'
            if (!document.getElementById(id)) {
                const btn = document.createElement('button')
                btn.id = id
                btn.innerText = '自动抽奖'
                btn.onclick = async () => {
                    btn.style.display = 'none'
                    await autoGacha()
                }
                document.querySelector('.bg_dec').appendChild(btn)
            }
        }
        // 当前处于游戏界面，添加自动拼图按钮
        if (pathname === '/lydjypt/game') {
            const id = 'auto_play'
            if (!document.getElementById(id)) {
                const btn = document.createElement('button')
                btn.id = id
                btn.innerText = '自动拼图'
                btn.onclick = async () => {
                    btn.style.display = 'none'
                    await autoPlay()
                    // await refresh()
                    // btn.style.display = ''
                }
                document.querySelector('.bg_dec').appendChild(btn)
            }
        }

    }, 500)
})();
